<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>房型预订</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        body {
            background: #f5f6fa;
            font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            color: #333;
            margin: 0;
        }
        .order-container {
            max-width: 420px;
            margin: 48px auto 0 auto;
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 6px 32px #b3a6e6;
            padding: 40px 36px 32px 36px;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        .order-title {
            text-align: center;
            font-size: 28px;
            font-weight: 800;
            color: #5a3ec8;
            margin-bottom: 32px;
            letter-spacing: 1.5px;
        }
        .room-info-card {
            background: #eaf2ff;
            border-left: 5px solid #5a3ec8;
            border-radius: 10px;
            padding: 18px 22px 14px 22px;
            margin-bottom: 28px;
            font-size: 16px;
            color: #333;
        }
        .room-info-card .room-title {
            font-size: 20px;
            font-weight: 700;
            color: #5a3ec8;
            margin-bottom: 6px;
        }
        .room-info-card .room-desc {
            color: #888;
            font-size: 15px;
            margin-top: 6px;
        }
        .order-form label {
            font-size: 16px;
            color: #555;
            margin-bottom: 6px;
            font-weight: 500;
            display: block;
        }
        .order-form input[type='text'],
        .order-form input[type='date'] {
            width: 100%;
            padding: 12px 14px;
            border: 1.5px solid #e0e7ff;
            border-radius: 8px;
            font-size: 16px;
            margin-bottom: 18px;
            outline: none;
            transition: border 0.2s;
            background: #fafaff;
        }
        .order-form input[type='text']:focus,
        .order-form input[type='date']:focus {
            border-color: #5a3ec8;
            background: #f5f7ff;
        }
        .order-form button[type='submit'] {
            width: 100%;
            background: #5a3ec8;
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 14px 0;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            margin-top: 10px;
            margin-bottom: 10px;
            transition: background 0.2s;
            letter-spacing: 1px;
            box-shadow: 0 2px 8px #e0d7f7;
        }
        .order-form button[type='submit']:hover {
            background: #764ba2;
        }
        .back-link {
            display: block;
            text-align: center;
            color: #5a3ec8;
            font-size: 15px;
            margin-top: 10px;
            text-decoration: none;
            transition: color 0.2s;
        }
        .back-link:hover {
            color: #f5576c;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="order-container">
        <div class="order-title">房型预订</div>
        
        <!-- 房型信息显示区域 -->
        <div id="roomTypeInfo" class="room-info-card" style="display: none;">
            <div class="room-title" id="roomTypeName">加载中...</div>
            <div class="room-desc" id="roomTypeDesc">正在获取房型信息...</div>
        </div>
        
        <form class="order-form">
            <label>入住时间</label>
            <input type="date" name="checkin">
            <label>离开时间</label>
            <input type="date" name="checkout">
            <label>姓名</label>
            <input type="text" name="name">
            <label>联系方式</label>
            <input type="text" name="contact">
            <button type="submit">提交预订</button>
        </form>
        
        <div id="orderResult" style="margin-top:20px;text-align:center;"></div>
        
        <div class="back-link">
            <a href="hotel.html">← 返回房型列表</a>
        </div>
    </div>
    <script>
        var roomTypeInfo = null;
        
        // 页面加载时获取房型信息
        $(document).ready(function() {
            function getQueryParam(name) {
                const url = window.location.search;
                const params = new URLSearchParams(url);
                return params.get(name);
            }
            var typeId = getQueryParam('typeId');
            
            // 设置入住时间最小为今天
            var today = new Date();
            var yyyy = today.getFullYear();
            var mm = (today.getMonth() + 1).toString().padStart(2, '0');
            var dd = today.getDate().toString().padStart(2, '0');
            var todayStr = yyyy + '-' + mm + '-' + dd;
            $('input[name="checkin"]').attr('min', todayStr);
            
            if (typeId) {
                // 获取房型信息
                $.ajax({
                    url: 'http://localhost:8080/api/roomtype/list',
                    type: 'GET',
                    success: function(data) {
                        roomTypeInfo = data.find(item => item.typeId == typeId);
                        if (roomTypeInfo) {
                            console.log('房型信息:', roomTypeInfo);
                            // 显示房型信息
                            $('#roomTypeName').text(roomTypeInfo.typeName);
                            $('#roomTypeDesc').html(`
                                <strong>床型：</strong>${roomTypeInfo.bedType} | 
                                <strong>面积：</strong>${roomTypeInfo.areaSize} | 
                                <strong>楼层：</strong>${roomTypeInfo.floorInfo}<br>
                                <strong>描述：</strong>${roomTypeInfo.description || '暂无描述'}
                            `);
                            $('#roomTypeInfo').show();
                            
                            // 更新页面标题
                            document.title = roomTypeInfo.typeName + ' - 预订';
                        } else {
                            $('#roomTypeName').text('房型信息获取失败');
                            $('#roomTypeDesc').text('请检查房型ID是否正确');
                            $('#roomTypeInfo').show();
                        }
                    },
                    error: function() {
                        console.log('获取房型信息失败');
                        $('#roomTypeName').text('房型信息获取失败');
                        $('#roomTypeDesc').text('网络连接异常，请稍后重试');
                        $('#roomTypeInfo').show();
                    }
                });
            } else {
                $('#roomTypeName').text('未选择房型');
                $('#roomTypeDesc').text('请从房型列表中选择要预订的房型');
                $('#roomTypeInfo').show();
            }
        });
        
        // 计算住宿天数和总金额
        function calculateTotal() {
            var checkIn = $('input[name="checkin"]').val();
            var checkOut = $('input[name="checkout"]').val();
            
            if (checkIn && checkOut && roomTypeInfo) {
                var checkInDate = new Date(checkIn);
                var checkOutDate = new Date(checkOut);
                
                // 计算天数差
                var timeDiff = checkOutDate.getTime() - checkInDate.getTime();
                var daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
                
                if (daysDiff > 0) {
                    var totalAmount = roomTypeInfo.pricePerNight * daysDiff;
                    
                    // 显示价格信息
                    $('#priceDetails').html(`
                        <div class="price-detail">
                            <span>房型：${roomTypeInfo.typeName}</span>
                        </div>
                        <div class="price-detail">
                            <span>每晚价格：</span>
                            <span>¥${roomTypeInfo.pricePerNight.toFixed(2)}</span>
                        </div>
                        <div class="price-detail">
                            <span>住宿天数：</span>
                            <span>${daysDiff}天</span>
                        </div>
                    `);
                    
                    $('#totalAmount').text('¥' + totalAmount.toFixed(2));
                    $('#priceInfo').show();
                } else {
                    $('#priceInfo').hide();
                }
            } else {
                $('#priceInfo').hide();
            }
        }
        
        // 自动校正离开时间
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        function getNextDayStr(dateStr) {
            var date = new Date(dateStr);
            date.setDate(date.getDate() + 1);
            return date.getFullYear() + '-' + padZero(date.getMonth() + 1) + '-' + padZero(date.getDate());
        }
        
        // 入住时间变化时自动调整离开时间
        $('input[name="checkin"]').on('change', function() {
            var checkIn = $('input[name="checkin"]').val();
            var checkOut = $('input[name="checkout"]').val();
            if (checkIn) {
                if (!checkOut || new Date(checkOut) <= new Date(checkIn)) {
                    var nextDayStr = getNextDayStr(checkIn);
                    $('input[name="checkout"]').val(nextDayStr);
                    // 移除alert提示
                }
            }
            calculateTotal();
        });
        // 离开时间变化时自动校正
        $('input[name="checkout"]').on('change', function() {
            var checkIn = $('input[name="checkin"]').val();
            var checkOut = $('input[name="checkout"]').val();
            if (checkIn && checkOut && new Date(checkOut) <= new Date(checkIn)) {
                var nextDayStr = getNextDayStr(checkIn);
                $('input[name="checkout"]').val(nextDayStr);
                // 移除alert提示
            }
            calculateTotal();
        });
        
        // 监听日期变化
        $('input[name="checkin"], input[name="checkout"]').on('change', calculateTotal);
        
        $('.order-form').on('submit', function(e) {
            e.preventDefault();
            var checkIn = $('input[name="checkin"]').val();
            var checkOut = $('input[name="checkout"]').val();
            var username = $('input[name="name"]').val().trim();
            var contactPhone = $('input[name="contact"]').val().trim();
            // 校验入住时间不能早于今日
            var today = new Date();
            var yyyy = today.getFullYear();
            var mm = (today.getMonth() + 1).toString().padStart(2, '0');
            var dd = today.getDate().toString().padStart(2, '0');
            var todayStr = yyyy + '-' + mm + '-' + dd;
            if (checkIn < todayStr) {
                $('#orderResult').text('入住时间不能早于今日');
                return;
            }
            if(!checkIn || !checkOut || !username || !contactPhone) {
                $('#orderResult').text('请填写完整信息');
                return;
            }
            var checkInTime = checkIn + ' 至 ' + checkOut;

            function getQueryParam(name) {
                const url = window.location.search;
                const params = new URLSearchParams(url);
                return params.get(name);
            }
            var typeId = getQueryParam('typeId');

            var userId = sessionStorage.getItem('userId'); // 登录时存储

            $.ajax({
                url: 'http://localhost:8080/api/order/create',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    userId: userId ? parseInt(userId) : 1, // 没有就用1（测试用，实际应强制登录）
                    username: username,
                    contactPhone: contactPhone,
                    checkInTime: checkInTime,
                    roomTypeId: typeId ? parseInt(typeId) : null
                }),
                success: function(res) {
                    if(res === 'success') {
                        $('#orderResult').text('预订成功，正在返回房型页面...');
                        setTimeout(function() {
                            window.location.href = 'hotel.html';
                        }, 1000);
                    } else {
                        $('#orderResult').text('预订失败，请重试');
                    }
                },
                error: function() {
                    $('#orderResult').text('请求失败，请稍后重试');
                }
            });
        });
    </script>
</body>
</html> 